<?php
/**
 * Created by PhpStorm.
 * User: jason
 * Date: 2017/11/7
 * Time: 0:05
 */

namespace Home\Controller;

use Common\Util\HttpClient;
use Home\Service\AlipayOrderService;
use Home\Service\OrderService;
use http\Env\Response;
use Think\Exception;
use Think\Log;

class OrderController extends HomeController
{
    /**
     * 生成微信支付二维码链接
     */
    public function wxPayment()
    {
        $param = I('param.');
        $service = new OrderService();
        try {
            $service->validateParam($param);
        } catch (\Exception $e) {
            $return['code'] = 600;
            $return['msg'] = $e->getMessage();
            $this->ajaxReturn($return);
        }
        //生成预支付订单
        $unifiedorder = $service->unifiedorder($param, $outTradeNo);

        $xmlData = arrayToXml($unifiedorder);
        $url = 'https://api.mch.weixin.qq.com/pay/unifiedorder';
        $returnData = HttpClient::post($url, $xmlData);
        //校验返回的结果并转换为数组
        try {
            $returnData = $service->decryptData($returnData);
        } catch (\Exception $e) {
            $return['code'] = 600;
            $return['msg'] = $e->getMessage();
            $this->ajaxReturn($return);
        }
        $data['code_url'] = $returnData['code_url'];
        $data['order_no'] = $outTradeNo;
        //获取code_url
        $result['data'] = $data;
        $result['code'] = 200;
        $this->ajaxReturn($result);
    }

    /**
     * 响应微信支付结果通知
     * @param $param
     * @return bool
     */
    public function replyNotify()
    {
        Log::writeInfo('start to process Weixin response','wxReply');
        //获取xml数据
        $postXml = $GLOBALS["HTTP_RAW_POST_DATA"]; //接收微信参数
        if (empty($postXml)) {
            return false;
        }
        //step-1 : 验证签名是否一致
        Log::writeInfo('step-1: validate sign','wxReply');
        $service = new OrderService();
        $returnData = xmlToArray($postXml);
        $wx_sign = $returnData['sign'];
        Log::writeInfo('wxPostParam: '.json_encode($returnData), 'wxReply');
        unset($returnData['sign']);
        $valid_sign = $service->sign($returnData);
        if ($wx_sign == $valid_sign) {
            Log::writeInfo('validate sign pass, sign: '.json_encode($wx_sign),'wxReply');
            //更新订单状态
            $id = $service->updateOrder($returnData);
            if ($id === false) {
                $reply['return_code'] = 'FAIL';
                $reply['return_msg'] = '订单号错误';
            } elseif ($id === 0) {
                $reply['return_code'] = 'FAIL';
                $reply['return_msg'] = '订单金额不一致';
            } elseif ($id) {
                $reply['return_code'] = 'SUCCESS';
                $reply['return_msg'] = 'OK';
            }
        } else {
            Log::writeInfo('validate sign no pass! wx_sign: '.json_encode($wx_sign).'; valid_sign: '.json_encode($valid_sign), 'wxReply');
            $reply['return_code'] = 'FAIL';
            $reply['return_msg'] = '签名失败';
        }
        Log::writeInfo('reply message: ' . json_encode($reply),'wxReply');
        $reply = arrayToXml($reply);
        echo $reply;
    }

    /**
     * 生成微信支付二维码
     * @param $url
     */
    public function generalCode($url)
    {
        $level=3;
        $size=4;
        Vendor('phpqrcode.phpqrcode');
        $errorCorrectionLevel =intval($level) ;//容错级别
        $matrixPointSize = intval($size);//生成图片大小
        //生成二维码图片
        $object = new \QRcode();
        $object->png($url, false, $errorCorrectionLevel, $matrixPointSize, 2);
    }

    /**
     * 查询订单支付状态
     * @param $orderno
     */
    public function checkOrder($orderno, $type)
    {
        if (!$orderno) {
            $result['code'] = 600;
            $result['msg'] = '订单号错误';
            $this->ajaxReturn($result);
        }
        //查询系统订单状态
        $order = M('UserRechargeOrder')->where(['out_trade_no' => $orderno])->find();
        if (!$order) {
            $result['code'] = 600;
            $result['msg'] = '订单不存在';
            $this->ajaxReturn($result);
        }
        if ($order['pay_status'] == 0 && $type == 'wx') {
            //请求查询订单接口
            $service = new OrderService();
            try {
                $service->queryWxOrder($orderno);
                $result['code'] = 200;
                $result['msg'] = '订单支付完成';
            } catch (\Exception $e) {
                $result['code'] = 600;
                $result['msg'] = $e->getMessage();
            }
            $this->ajaxReturn($result);
        } /*elseif ($order['pay_status'] == 0 && $type == 'ali') { //todo:支付宝返回参数无用户选中套餐参数,逻辑待处理
            //支付宝订单支付状态
            $service = new OrderService();
            try {
                $service->queryAliOrder($orderno);
                $result['code'] = 200;
                $result['msg'] = '订单支付完成';
            } catch (\Exception $e) {
                $result['code'] = 600;
                $result['msg'] = $e->getMessage();
            }
            $this->ajaxReturn($result);
        }*/ elseif ($order['pay_status'] == 1) {
            $result['code'] = 200;
            $result['msg'] = '订单支付完成';
            $this->ajaxReturn($result);
        }
    }

    /**
     * 生成支付宝支付订单
     */
    public function aliPayOrderno()
    {
        $model = new OrderService();
        $orderno = $model->outTradeNo();
        if (!$orderno) {
            $return['code'] = 600;
            $return['msg'] = '生成订单失败';
        }
        $result['data'] = $orderno;
        $result['code'] = 200;
        $this->ajaxReturn($result);
    }

    /**
     * 发起支付宝支付,跳转支付宝支付链接
     */
    public function aliPayment()
    {
        $param = I('param.');
        Vendor('alipay.AopSdk');
        //支付宝支付配置
        $aop = new \AopClient();
        $aop->appId = C('ALIPAY.appid');
        $aop->rsaPrivateKey = C('ALIPAY.privateKey');
        $aop->signType = 'RSA2';
        //调用支付接口
        $request = new \AlipayTradePagePayRequest();
        $request->setNotifyUrl(C('ALIPAY.notify_url'));  //设置异步通知url
        $request->setReturnUrl(C('ALIPAY.return_url')); //设置同步通知url
        //获取订单参数
        $model = new OrderService();
        $bizContent = $model->getBizContent($param);
        if (!$bizContent) {
            echo '请求错误!请联系客服!';
            exit;
        }
        $request->setBizContent($bizContent);
        //发起订单请求
        $result = $aop->pageExecute($request);
        echo $result;
    }

    /**
     * 响应支付宝异步通知支付结果
     */
    public function aliNotify()
    {
        $param = I('param.');
        Vendor('alipay.AopSdk');
        //支付宝支付配置
        $aop = new \AopClient();
        $aop->appId = C('ALIPAY.appid');
        $aop->rsaPrivateKey = C('ALIPAY.privateKey');
        $aop->alipayrsaPublicKey = C('ALIPAY.aliPublicKey');
        $aop->signType = 'RSA2';
        //验签,确认通知来源合法
        $verify = $aop->rsaCheckV1($param, NULL, 'RSA2');
        if($verify){
            //验签成功后，按照支付结果异步通知中的描述，对支付结果中的业务内容进行二次校验，校验成功后在response中返回success并继续商户自身业务处理，校验失败返回failure
            $service = new OrderService();
            $result = $service->updateAliOrder($param);
            if ($result) {
                echo 'success';
            } else {
                echo 'failure';
            }
        }else{
            // 验签失败,记录异常日志，并在response中返回failure.
            Log::writeInfo('Sign verify failure', 'aliPayReply');
            echo 'failure';
        }

    }

    /**
     * 响应支付宝同步通知支付结果
     */
    public function aliReturnUrl()
    {
        $this->display('order/return');
    }

}